package ift604.projet.stereomood;


import static ift604.projet.music.Playlist.playListFromStereoMoodJSON;
import ift604.projet.feeling.Feeling;
import ift604.projet.music.Playlist;
import ift604.projet.music.PlaylistUpdatedListener;
import ift604.projet.oauth.OAuthCallback;
import ift604.projet.oauth.OAuthManager;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;

public class StereoMoodAPI implements OAuthCallback {

	static String API_KEY = "5f1c4bf6de1c9addefa81674da6059b304e93553e";
	static String SECRET_KEY = "11f94c7a4a14aaa0809467bbf938b57a";

	public static final String REQUEST_URL = "http://stereomood.com/api/oauth/request_token";
	public static final String ACCESS_URL = "http://stereomood.com/api/oauth/access_token";
	public static final String AUTHORIZE_URL = "http://stereomood.com/api/oauth/authenticate";

	private OAuthManager oAuthManager;
	private StereoMoodAPICommand commandToExecute;
	private List<PlaylistUpdatedListener> playListUpdatedListeners = new ArrayList<PlaylistUpdatedListener>();


	public StereoMoodAPI(Activity mainActivity) {
		oAuthManager = new OAuthManager(mainActivity, API_KEY, SECRET_KEY, REQUEST_URL, ACCESS_URL, AUTHORIZE_URL, Constants.OAUTH_CALLBACK_SCHEME, Constants.OAUTH_CALLBACK_HOST);
	}

	public void addPlayListUpdatedListener(PlaylistUpdatedListener listener) {
		playListUpdatedListeners.add(listener);
	}

	public void buildPlaylistOfFeeling(Feeling emotion) {
		authenticationSafeOperation(new BuildPlaylistOfFeeling(emotion));
	}

	private boolean isNetworkAvailable() { 
		ConnectivityManager connectivityManager  
		= (ConnectivityManager) oAuthManager.mainActivity.getSystemService(Context.CONNECTIVITY_SERVICE); 
		NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); 
		return activeNetworkInfo != null; 
	} 

	private void authenticationSafeOperation(StereoMoodAPICommand command) {
		commandToExecute = command;

		if (!isNetworkAvailable()) {
			authenticationFailure();
			return;
		}

		if (oAuthManager.isAuthenticated()) {
			//command.execute();
			authenticationSuccess();
			return;
		}

		oAuthManager.authenticate(this);
	}

	@Override
	public void authenticationSuccess() {
		new AsyncTask<Void, Void, Void>() {
			@Override
			protected Void doInBackground(Void... params) {
				commandToExecute.execute();
				return null;
			}
		}.execute();
		
		//commandToExecute.execute();
	}

	@Override
	public void authenticationFailure() {
		new AsyncTask<Void, Void, Void>() {
			@Override
			protected Void doInBackground(Void... params) {
				commandToExecute.connectionFailed();
				return null;
			}
		}.execute();

		//commandToExecute.connectionFailed();
	}

	private class BuildPlaylistOfFeeling extends StereoMoodAPICommand {
		Feeling feeling;

		public BuildPlaylistOfFeeling(Feeling feeling) {
			this.feeling = feeling;
		}

		@Override
		public void execute() {
			try {
				String result = oAuthManager.sendRequestToURL("http://www.stereomood.com/api/search.json?q=" + feeling.nameForStereoMood() + "&type=mood");
				JSONObject json = (JSONObject) new JSONParser().parse(result);
				JSONArray songsAsJson= (JSONArray) json.get("songs");
				notifyPlaylistUpdated(playListFromStereoMoodJSON(songsAsJson));
			} catch (ParseException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			} 
		}

		private void notifyPlaylistUpdated(Playlist updatedPlaylist){
			for(PlaylistUpdatedListener listener: playListUpdatedListeners){
				listener.playlistUpdated(updatedPlaylist);
			}
		}

		@Override
		public void connectionFailed() {
			for(PlaylistUpdatedListener listener: playListUpdatedListeners){
				listener.playlistUpdateFailed();
			}
		}
	}
}
